import { useRouter } from 'vue-router'
import { RequestLogin } from '@/api/login'
import { ref } from 'vue'
import { userStore } from '@/stores/user'
import { Toast } from 'vant'


/**
 * 登录业务
 */
export const userLogin = () => {
    const store = userStore()
    let user = ref(store.userInfo);
    const router = useRouter()
    // const storeUser=userStore()
    const username = ref('')
    const password = ref('')
    const onSubmit = async values => {
        let data = await RequestLogin(values.username, values.password)
        let { resultCode, resultInfo, token } = data
        if (resultCode == 1) {
            // 保存用户信息
            store.saveUser({ nick: resultInfo.nick, headerimg: resultInfo.headerimg })
            // console.log(user.value.nick)
            // 保存token
            localStorage.setItem('TOKEN', token)
            // localStorage.getItem(token)
            console.log('存储的token',token);       
            user.value = store.userInfo;
            console.log(user.value.nick);
              
            // 跳转回个人中心
            router.replace({ path: '/user' })
           
        }
        else {
            Toast.fail('用户名或密码出错！')
        }
    }
    const onClickLeft = () => {
        history.back()
    }

    return {
        onSubmit,
        onClickLeft,
        username,
        password,
        user
    }


}

